package com.srwl.mytx.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.ChatRoomActivity;
import com.srwl.mytx.activity.EditTopicActivity;
import com.srwl.mytx.activity.ForwardDonationActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.activity.TopicRecordActivity;
import com.srwl.mytx.activity.TransferAuthorityActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.BottomDialog;
import com.srwl.mytx.widget.ConfirmDialog;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 主题网格显示适配器
 */

public class TopicGridAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "TopicGridAdapter";
    private final List<Topic> topicList;
    private long lastClickTime;
    private final Context context;
    private final int density;
    private InteractionListener listener;
    private boolean bol_noData;//标记是否有数据
    private boolean bol_requestError;//标记是否有数据


    public TopicGridAdapter(List<Topic> topicList, Context context) {
        this.topicList = topicList;

        this.context = context;
        density = (int) context.getResources().getDisplayMetrics().density;
    }

    @Override
    public int getItemCount() {
        if (bol_noData || bol_requestError) {
            return 1;
        }
        return topicList.size();
    }


    @Override
    public int getItemViewType(int position) {
        if (bol_noData) {
            return Constant.ITEM_TYPE_NO_DATA;
        } else if (bol_requestError) {
            return Constant.ITEM_TYPE_REQUEST_ERROR;
        }
        return Constant.ITEM_TYPE_NORMAL;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            return new NoDataViewHolder(LayoutInflater.from(context).inflate(R.layout.no__data__layout, parent, false));
        } else if (viewType == Constant.ITEM_TYPE_REQUEST_ERROR) {
            return new RequestErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.request_error_layout, parent, false));
        }
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_topic_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        int viewType = getItemViewType(position);
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            ((NoDataViewHolder) holder).tv_tips.setText("没有发布记录");
            return;
        } else if (viewType == Constant.ITEM_TYPE_NORMAL) {

            ViewHolder viewHolder = (ViewHolder) holder;
            GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
            if (position < 2) {
                switch (position) {
                    case 0:
                        layoutParams.rightMargin = 1 * density;
                        break;
                    case 1:
                        layoutParams.leftMargin = 1 * density;
                }
            } else {
                switch (position % 2) {
                    case 0:
                        layoutParams.rightMargin = 1 * density;
                        break;
                    case 1:
                        layoutParams.leftMargin = 1 * density;
                }
            }
            layoutParams.bottomMargin = 2 * density;
            final Topic topic = topicList.get(position);
            String title = topic.getTitle();
            final Integer status = topic.getStatus();
            if (status == Constant.TOPIC_STATUS_WAIT_VERIFY) {
                title = "[审核中] " + title;
            } else if (status == Constant.TOPIC_STATUS_VERIFY_FAIL) {
                title = "[审核未通过] " + title;
            }
            viewHolder.tv_title.setText(title);
            if (!TextUtils.isEmpty(topic.getVideo())) {
                // String video = topic.getVideo();
                String coverUrl = Utils.getTopicListPreviewUrl(topic);
//                String videoCover = topic.getVideoCover();
//                if (!TextUtils.isEmpty(videoCover)) {
//                    coverUrl = AliOssService.TOPIC_IMAGE_PRE_URL + videoCover;
//                } else if (video != null && video.startsWith("http")) {
//                    coverUrl = video;
//                } else {
//                    coverUrl = AliOssService.TOPIC_VIDEO_PRE_URL + video;
//                }
                //Glide.with(context).load(coverUrl).diskCacheStrategy(DiskCacheStrategy.ALL).into(viewHolder.iv_picture);
                GlideLoadUtils.glideLoad(context, coverUrl, viewHolder.iv_picture);
            } else if (topic.getPictures() != null && topic.getPictures().size() != 0) {
                String image = topic.getPictures().get(0);
                String imageUrl;
                if (image != null && image.startsWith("http")) {
                    imageUrl = image;
                } else {
                    imageUrl = AliOssService.TOPIC_IMAGE_PRE_URL + image;
                }
                // Glide.with(context).load(imageUrl).diskCacheStrategy(DiskCacheStrategy.ALL).into(viewHolder.iv_picture);
                GlideLoadUtils.glideLoad(context, imageUrl, viewHolder.iv_picture);

            } else if (!TextUtils.isEmpty(topic.getContent())) {
                viewHolder.tv_title.setTextColor(context.getResources().getColor(R.color.text_gray));
            }
            //使直播间类型的Topic显示跳转直播间的图标，悬赏和曝光不显示该图标
            switch (topic.getType()) {
                case Constant.TOPIC_TYPE_EXPOSE:
                case Constant.TOPIC_TYPE_REWARD:
                    viewHolder.iv_liveRoom.setVisibility(View.GONE);
                    break;
                case Constant.TOPIC_TYPE_AREA:
                case Constant.TOPIC_TYPE_INDUSTRY:
                case Constant.TOPIC_TYPE_SCHOOL:
                    viewHolder.iv_liveRoom.setVisibility(View.VISIBLE);
                    break;
            }

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (listener.onItemClick(position)) {
                        return;
                    }
                    if (ClickUtil.isFastClick()) return;
                    context.startActivity(new Intent(context, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));

                }
            });

            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                    List<String> itemStrings = Utils.generateTopicBottomDialogItems(topic);
                    if (itemStrings.size() == 0) {
                        return false;
                    }
                    showBottomDialog(itemStrings, topic, holder.getAdapterPosition());
                    return true;
                }
            });

            //给电视机图标注册点击事件
            viewHolder.iv_liveRoom.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ClickUtil.isFastClick()) return;
                    //组合聊天室数据
                    LiveRoom liveRoom = new LiveRoom();
                    liveRoom.setId(topic.getId());
                    liveRoom.setManagerId(topic.getManagerId());
                    liveRoom.setChatId(topic.getId());
                    liveRoom.setTitle(topic.getTitle());
                    liveRoom.setStatus(topic.getStatus());
                    liveRoom.setVideo(topic.getVideo());
                    if (topic.getPictures() != null && topic.getPictures().size() != 0) {//图片和视频，至少有一样存在
                        liveRoom.setCover(topic.getPictures().get(0));
                    } else {
                        liveRoom.setCover(topic.getVideoCover());
                    }
                    //跳转到当前主题的聊天室活动中
                    context.startActivity(new Intent(context, ChatRoomActivity.class).putExtra(Constant.EXTRA_INFO_LIVE_ROOM, liveRoom));
                }
            });
        }
    }

    private void showBottomDialog(List<String> itemStrings, Topic topic, int itemPosition) {
        BottomDialog dialog = new BottomDialog(context, itemStrings);
        dialog.show();
        dialog.setListener(new BottomDialog.InteractionListener() {
            @Override
            public void onDialogItemViewClick(final int position, String itemName) {
                switch (itemName) {
                    case Constant.BOTTOM_ITEM_NAME_EDIT:
                        //如果是悬赏类型的主题，且悬赏任务正在执行中，不能编辑
                        if (topic.getType() != null && topic.getType() == Constant.TOPIC_TYPE_REWARD && topic.getStatus() == Constant.TOPIC_STATUS_REWARD_EXECUTING) {
                            showToast("悬赏任务正在执行中，不能编辑");
                            return;
                        }
                        ((Activity) context).startActivityForResult(new Intent(context, EditTopicActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), TopicRecordActivity.REQUEST_CODE_EDIT_TOPIC);
                        break;
                    case Constant.BOTTOM_ITEM_NAME_DELETE:
                        ConfirmDialog confirmDialog = new ConfirmDialog(context, "提醒", "确认删除吗？", true);
                        confirmDialog.show();
                        confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                            @Override
                            public void confirm() {
                                deleteTopic(topic, itemPosition);
                            }
                        });
                        break;
                    case Constant.BOTTOM_ITEM_NAME_REVOKE_REWARD:
                        //如果是悬赏类型的主题，且悬赏任务正在执行中，不能编辑
                        if (topic.getStatus() == Constant.TOPIC_STATUS_REWARD_EXECUTING) {
                            showToast("悬赏任务正在执行中，不能拆回悬赏");
                            return;
                        }
                        ConfirmDialog dialog = new ConfirmDialog(context, "提醒", "确认撤回悬赏,退回保证金吗？", true);
                        dialog.show();
                        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                            @Override
                            public void confirm() {
                                revokeReward(topic);
                            }
                        });
                        break;
                    case Constant.BOTTOM_ITEM_NAME_MANAGE_DONATION:
                        ((Activity) context).startActivityForResult(new Intent(context, ForwardDonationActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), TopicRecordActivity.REQUEST_CODE_EDIT_TOPIC);
                        break;
                    case Constant.BOTTOM_ITEM_EXIT_MANAGER:
                        ConfirmDialog confirmDialogExit = new ConfirmDialog(context, "提醒", "确认放弃管理权限吗?", true);
                        confirmDialogExit.show();
                        confirmDialogExit.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                            @Override
                            public void confirm() {
                                exitManagerTopic(topic, itemPosition);
                            }
                        });
                        break;
                    case Constant.BOTTOM_ITEM_SURRENDER_MANAGER:
                        ((Activity) context).startActivityForResult(new Intent(context, TransferAuthorityActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), TopicRecordActivity.REQUEST_CODE_DELETE_TOPIC);
                        break;
                }
            }
        });
    }


    /**
     * 删除主题
     *
     * @param topic
     */
    void deleteTopic(Topic topic, final int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        if (listener != null) {
            listener.showProgress(true);
        }
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .delete_v1(topic.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (listener != null) {
                            listener.showProgress(false);
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (listener != null) {
                                listener.showToast(context.getResources().getString(R.string.system_busy));
                            }
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.TOPIC_TYPE_ERROR:
                                    showToast("主题类型错误，不能删除");
                                    break;
                                case Constant.TOPIC_STATUS_ERROR:
                                    showToast("主题状态错误，不能删除");
                                    break;
                                default:
                                    showToast("系统繁忙,请稍后重试");
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 删除完成");

                        if (listener != null) {
                            listener.showToast(context.getString(R.string.delete_topic_complete));
                        }
                        topicList.remove(topic);
                        notifyItemRemoved(position);    //只是执行动画,onBindViewHolder不会调用，只调用该方法会导致position错乱
                        notifyItemRangeChanged(position, topicList.size() - position);  //通知RecyclerView执行实际的删除操作
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (listener != null) {
                            listener.showProgress(false);
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        if (listener != null) {
                            listener.showToast(context.getResources().getString(R.string.system_busy));
                        }
                    }
                });
    }

    void exitManagerTopic(Topic topic, final int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        if (listener != null) {
            listener.showProgress(true);
        }
        //调用服务器端的接口完成退出管理操作
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .giveUpManager(topic.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (listener != null) {
                            listener.showProgress(false);
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast("系统繁忙");
                            return;
                        }
                        if (result.isError()) {
                            Log.i(TAG, "onResponse:" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.NO_AUTHORITY:
                                    showToast("你不是管理员,权限不足");
                                    break;
                                case Constant.TOPIC_TYPE_ERROR:
                                    showToast("主题类型错误,不能退出管理");
                                    break;
                                case Constant.TOPIC_STATUS_ERROR:
                                    showToast("该主题目前是管理员空缺状态，不能进行此操作，如有疑问，请联系客服");
                                    break;
                                default:
                                    showToast("系统繁忙,请稍后重试");
                            }
                            return;
                        }
                        showToast("退出管理完成");
                        topicList.remove(topic);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, topicList.size() - position);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (listener != null) {
                            listener.showProgress(false);
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast("系统出现错误");
                    }
                });

    }

    void revokeReward(Topic topic) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        if (listener != null) {
            listener.showProgress(true);
        }
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .revokeReward(topic.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (listener != null) {
                            listener.showProgress(false);
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast("系统繁忙");
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.REWARD_TOPIC_ALREADY_CANCEL:
                                    showToast("主题已经撤回,不可重复撤回");
                                    break;
                                case Constant.REWARD_TOPIC_STATUS_ERROR:
                                    showToast("还有任务正在执行中,不能撤回");
                                    break;
                                default:
                                    showToast("系统繁忙,请稍后重试");
                            }
                            return;
                        }
                        double deposit = ((BigDecimal) result.getData()).doubleValue();
                        UserProfileManager.getInstance().setDeposit(deposit);
                        topic.setStatus(Constant.TOPIC_STATUS_REWARD_CANCEL);
                        showToast("撤回悬赏成功，保证金已退回");

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (listener != null) {
                            listener.showProgress(false);
                        }
                        Log.i(TAG, "onFailure:" + t.getMessage());
                        showToast("系统错误");
                    }
                });
    }


    class NoDataViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_tips)
        TextView tv_tips;

        public NoDataViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    private void getFullUserInfo(String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User userInfo = object.toJavaObject(User.class);
                        userInfo.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(userInfo);
                        context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        // showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });


    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.iv_picture)
        ImageView iv_picture;
        @BindView(R.id.iv_live_room)
        ImageView iv_liveRoom;
        public Topic topic;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);

        }

    }

    /**
     * 弹出提示
     */
    public void showToast(String message) {
        View view = ((Activity) context).getWindow().getDecorView();
        showToast(view, message);
    }

    public void showToast(final View view, final String toastContent) {
        ((Activity) context).runOnUiThread(new Runnable() {
            public void run() {
                // Toast.makeText(BaseActivity.this, toastContent, Toast.LENGTH_SHORT).show();
                // Snackbar.make(getWindow().getDecorView(), toastContent, Snackbar.LENGTH_LONG).show(); //这样虽然方便了，不用传view 参数进来，弊端：当键盘打开的时候，键盘会遮住Snackbar;
                Snackbar.make(view, toastContent, Snackbar.LENGTH_LONG).show();
            }
        });
    }


    /**
     * 显示普通视图
     * 有数据的时候调用
     */
    public void showNormalView() {
        bol_noData = false;
        bol_requestError = false;
        notifyDataSetChanged();
    }

    public void showNormalView(int positionStart, int itemCount) {
        bol_noData = false;
        bol_requestError = false;
        notifyItemRangeInserted(positionStart, itemCount);
    }


    /**
     * 显示无数据视图
     */
    public void showNoDataView() {
        bol_noData = true;
        notifyDataSetChanged();
    }

    /**
     * 显示请求数据错误视图
     */
    public void showErrorView() {
        bol_requestError = true;
        notifyDataSetChanged();
    }


    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {

        boolean onItemClick(int position);

        void showProgress(boolean isShowProgress);

        void showToast(String content);

        void onDeleteTopic(int position);

    }
}
